package com.example.consumer.controller;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.example.consumer.client.UserClient;
import com.example.consumer.config.Result;
import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * \* @author: bear
 * \* Date: 2022-04-07-15:56
 * \* describe:
 */
@RestController
@Slf4j
//默认的回退机制，不带参数
@DefaultProperties(defaultFallback = "defaultFallback")
public class ConsumerController {

	@GetMapping("rest/userinfo")
	@HystrixCommand
	public Result getRest(@RequestParam String username) {
		RestTemplate restTemplate = new RestTemplate();
		String url = String.format("http://127.0.0.1:8763/index/userinfo?username=%s", username);
		Result forObject = restTemplate.getForObject(url, Result.class);
		log.debug(JSONUtil.toJsonStr(forObject));
		return forObject;
	}

	@Resource
	private RestTemplate restTemplate;

	@GetMapping("rest/userinfoTwo")
	// @HystrixCommand(fallbackMethod = "fallback")
	public Result userinfoTwo(@RequestParam String username, HttpServletRequest request) {
		Cookie[] cookies = request.getCookies();
		String url = String.format("http://USER-INFO/index/userinfo?username=%s", username);
		Result forObject = restTemplate.getForObject(url, Result.class);
		log.debug(JSONUtil.toJsonStr(forObject));
		return forObject;
	}

	@Resource
	private UserClient userClient;

	@GetMapping("rest/userinfoThree")
	@HystrixCommand(fallbackMethod = "fallback")
	public Result userinfoThree(@RequestParam String username) {
		int aaa = 1 > 2 ? 0 : 3;
		Result forObject = userClient.getuserInfo(username);
		log.debug(JSONUtil.toJsonStr(forObject));
		return forObject;
	}

	private Result fallback(String username) {
		return Result.failed("4000", "太拥挤了，请稍候再试~~");
	}

	//默认回退机制不能带参数
	private Result defaultFallback() {
		return Result.failed("4000", "太拥挤了222，请稍候再试~~");
	}
}
